<?php

namespace app\api\controller;
use think\facade\Lang;
/**
 * ============================================================================
 * DSShop单店铺商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 下单控制器
 */
class Memberbuy extends MobileMember
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/'.config('lang.default_lang').'/buy.lang.php');
    }

    /**
     * @api {POST} api/Memberbuy/buy_step1 购物车、直接购买第一步:选择收获地址和配置方式
     * @apiVersion 3.0.6
     * @apiGroup MemberBuy
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} cart_id 购买ID
     * @apiParam {String} ifcart 购买数据
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.address_api  运费信息
     * @apiSuccess {Object} result.address_api.content  运费列表
     * @apiSuccess {String} result.address_api.state  状态 success成功fail失败
     * @apiSuccess {Object} result.address_info  地址信息
     * @apiSuccess {String} result.address_info.address_detail  收货人信息地址
     * @apiSuccess {Int} result.address_info.address_id  地址ID
     * @apiSuccess {String} result.address_info.address_is_default  默认地址 1是0否
     * @apiSuccess {String} result.address_info.address_latitude  纬度
     * @apiSuccess {String} result.address_info.address_longitude  经度
     * @apiSuccess {String} result.address_info.address_mob_phone  收货人手机号
     * @apiSuccess {String} result.address_info.address_realname  收货人真实姓名
     * @apiSuccess {String} result.address_info.address_tel_phone  收货人座机号
     * @apiSuccess {Int} result.address_info.area_id  地区ID
     * @apiSuccess {String} result.address_info.area_info  地区信息
     * @apiSuccess {Int} result.address_info.city_id  城市ID
     * @apiSuccess {Int} result.address_info.dlyp_id  自提点ID
     * @apiSuccess {Int} result.address_info.member_id  用户ID
     * @apiSuccess {Float} result.available_predeposit  可用预存款余额
     * @apiSuccess {Float} result.available_rc_balance  充值卡余额
     * @apiSuccess {String} result.freight_hash  运费哈希值
     * @apiSuccess {Object} result.inv_info  发票信息
     * @apiSuccess {String} result.inv_info.content  发票信息描述
     * @apiSuccess {Boolean} result.member_paypwd  已设置支付密码 true是false否
     * @apiSuccess {Float} result.order_amount  订单总价
     * @apiSuccess {Object} result.cart_list  购物车信息
     * @apiSuccess {Object[]} result.cart_list.goods_list  商品列表
     * @apiSuccess {Int} result.cart_list.goods_list.bl_id  优惠套餐ID
     * @apiSuccess {Int} result.cart_list.goods_list.buyer_id  买家ID
     * @apiSuccess {Int} result.cart_list.goods_list.cart_id  购物车ID
     * @apiSuccess {Int} result.cart_list.goods_list.gc_id  分类ID
     * @apiSuccess {Int} result.cart_list.goods_list.goods_commonid  商品公共ID
     * @apiSuccess {Float} result.cart_list.goods_list.goods_freight  运费
     * @apiSuccess {Int} result.cart_list.goods_list.goods_id  商品ID
     * @apiSuccess {String} result.cart_list.goods_list.goods_image  商品图片名称
     * @apiSuccess {String} result.cart_list.goods_list.goods_image_url  商品图片完整路径
     * @apiSuccess {String} result.cart_list.goods_list.goods_name  商品名称
     * @apiSuccess {Int} result.cart_list.goods_list.goods_num  购买数量
     * @apiSuccess {Float} result.cart_list.goods_list.goods_price  商品价格
     * @apiSuccess {Int} result.cart_list.goods_list.goods_storage  商品库存
     * @apiSuccess {Int} result.cart_list.goods_list.goods_storage_alarm  商品预警库存
     * @apiSuccess {Float} result.cart_list.goods_list.goods_total  商品总价
     * @apiSuccess {Boolean} result.cart_list.goods_list.goods_vat  是否支持发票 0否1是
     * @apiSuccess {Object} result.cart_list.goods_list.groupbuy_info  抢购信息
     * @apiSuccess {Int} result.cart_list.goods_list.is_goodsfcode  是否F码 0否1是
     * @apiSuccess {Int} result.cart_list.goods_list.is_have_gift  是否含赠品 0否1是
     * @apiSuccess {Object} result.cart_list.goods_list.mgdiscount_info  会员折扣信息
     * @apiSuccess {Boolean} result.cart_list.goods_list.state  商品状态 true上架false下架
     * @apiSuccess {Boolean} result.cart_list.goods_list.storage_state  库存状态 true足够false不足
     * @apiSuccess {Int} result.cart_list.goods_list.transport_id  售卖区域id
     * @apiSuccess {Object} result.cart_list.goods_list.xianshi_info  秒杀信息
     * @apiSuccess {Float} result.cart_list.goods_total  商品总价
     * @apiSuccess {Object} result.cart_list.mansong_rule_list  满赠列表
     * @apiSuccess {String} result.cart_list.mansong_rule_list.desc  满赠描述
     * @apiSuccess {String} result.cart_list.mansong_rule_list.discount  优惠金额
     * @apiSuccess {Int} result.cart_list.mansong_rule_list.goods_id  满就送商品ID
     * @apiSuccess {Int} result.cart_list.mansong_rule_list.mansong_endtime  满赠结束时间，Unix时间戳
     * @apiSuccess {String} result.cart_list.mansong_rule_list.mansong_goods_name  满就送礼品名称
     * @apiSuccess {Int} result.cart_list.mansong_rule_list.mansong_id  满赠ID
     * @apiSuccess {String} result.cart_list.mansong_rule_list.mansong_name  满赠名称
     * @apiSuccess {Int} result.cart_list.mansong_rule_list.mansong_starttime  满赠开始时间，Unix时间戳
     * @apiSuccess {Float} result.cart_list.mansong_rule_list.mansongrule_discount  优惠金额
     * @apiSuccess {Int} result.cart_list.mansong_rule_list.mansongrule_id  满就送规则ID
     * @apiSuccess {Float} result.cart_list.mansong_rule_list.mansongrule_price  最低消费金额
     * @apiSuccess {Object} result.cart_list.voucher_info  优先使用的优惠券信息
     * @apiSuccess {String} result.cart_list.voucher_info.desc  优惠券描述
     * @apiSuccess {String} result.cart_list.voucher_info.voucher_activedate  代金券发放日期，Unix时间戳
     * @apiSuccess {String} result.cart_list.voucher_info.voucher_code  代金券编码
     * @apiSuccess {String} result.cart_list.voucher_info.voucher_desc  优惠券详情
     * @apiSuccess {Int} result.cart_list.voucher_info.voucher_enddate  代金券有效期结束时间，Unix时间戳
     * @apiSuccess {String} result.cart_list.voucher_info.voucher_enddate_text  代金券有效期结束时间描述
     * @apiSuccess {Int} result.cart_list.voucher_info.voucher_id  优惠券ID
     * @apiSuccess {Float} result.cart_list.voucher_info.voucher_limit  优惠券最低金额
     * @apiSuccess {Int} result.cart_list.voucher_info.voucher_order_id  优惠券关联订单ID
     * @apiSuccess {Int} result.cart_list.voucher_info.voucher_owner_id  优惠券所属用户ID
     * @apiSuccess {String} result.cart_list.voucher_info.voucher_owner_name  优惠券所属用户名称
     * @apiSuccess {Float} result.cart_list.voucher_info.voucher_price  优惠金额
     * @apiSuccess {Int} result.cart_list.voucher_info.voucher_startdate  代金券有效期开始时间，Unix时间戳
     * @apiSuccess {Int} result.cart_list.voucher_info.voucher_state  代金券状态 1:未用 2:已用 3:过期 4:收回 
     * @apiSuccess {String} result.cart_list.voucher_info.voucher_title  优惠券标题
     * @apiSuccess {Int} result.cart_list.voucher_info.voucher_type  代金券类别
     * @apiSuccess {Int} result.cart_list.voucher_info.vouchertemplate_id  优惠券模板ID
     * @apiSuccess {Object[]} result.cart_list.voucher_list  优惠券列表
     * @apiSuccess {Object[]} result.cart_list_api  去除result.cart_list键的数组
     * @apiSuccess {Object} result.final_total_list  总价列表
     * @apiSuccess {Boolean} result.vat_deny  不支持发票 true是false否
     * @apiSuccess {String} result.vat_hash  不支持发票哈希值
     */
    public function buy_step1()
    {

        $cart_id = explode(',', input('param.cart_id'));

        $logic_buy = model('buy', 'logic');

        //得到会员等级
        $member_model = model('member');
        $member_info = $member_model->getMemberInfoByID($this->member_info['member_id']);
        if (!$member_info['is_buylimit']) {
            ds_json_encode(10001, '您没有商品购买的权限,如有疑问请联系客服人员');
        }
        if(config('ds_config.member_auth') && $this->member_info['member_auth_state']!=3){
            ds_json_encode(10001,lang('cart_buy_noauth'));
        }
        /*
          if ($member_info) {
          $member_gradeinfo = $member_model->getOneMemberGrade(intval($member_info['member_exppoints']));
          $member_discount = $member_gradeinfo['orderdiscount'];
          $member_level = $member_gradeinfo['level'];
          }
          else {
          $member_discount = $member_level = 0;
          } */

        //得到购买数据
        $ifcart = !empty(input('param.ifcart')) ? true : false;

        //额外数据用来处理拼团等其他活动
        $pintuan_id = intval(input('param.pintuan_id'));
        $extra = array();
        if ($pintuan_id >= 0) {
            $extra['pintuan_id'] = $pintuan_id; #拼团ID
            #是否为开团订单
            $extra['pintuangroup_id'] = empty(input('param.pintuangroup_id')) ? 0 : intval(input('param.pintuangroup_id'));
        }

        $result = $logic_buy->buyStep1($cart_id, $ifcart, $this->member_info['member_id'], $extra);

        if (!$result['code']) {
            ds_json_encode(10001, $result['msg']);
        } else {
            $result = $result['data'];
        }

        if (intval(input('post.address_id')) > 0) {
            $result['address_info'] = model('address')->getDefaultAddressInfo(array('address_id' => intval(input('post.address_id')), 'member_id' => $this->member_info['member_id']));
        }
        if ($result['address_info']) {
            $data_area = $logic_buy->changeAddr($result['freight_list'], $result['address_info']['city_id'], $result['address_info']['area_id'], $this->member_info['member_id']);
            if (!empty($data_area) && $data_area['state'] == 'success') {
                if (is_array($data_area['content'])) {
                    $data_area['content'] = ds_price_format($value);
                }
            } else {
                ds_json_encode(10001, '地区请求失败');
            }
        }

        //整理数据
        $cart_list = array();
        $total_list = $result['goods_total'];
            $cart_list['goods_list'] = $result['cart_list'];
            $cart_list['goods_total'] = $result['goods_total'];
            $cart_list['goods_original_total'] = $result['goods_original_total'];
            $cart_list['goods_discount_total'] = $result['goods_discount_total'];

            $cart_list['mansong_rule_list'] = (isset($result['mansong_rule_list']) && !empty($result['mansong_rule_list'])) ? $result['mansong_rule_list'] : '';

            if ($cart_list['mansong_rule_list'] && $cart_list['mansong_rule_list']['discount'] > 0) {
                $total_list -= $cart_list['mansong_rule_list']['discount'];
            }

            if (is_array($result['voucher_list']) && count($result['voucher_list']) > 0) {
                current($result['voucher_list']);
                $cart_list['voucher_info'] = reset($result['voucher_list']);
                $cart_list['voucher_info']['voucher_price'] = ds_price_format($cart_list['voucher_info']['voucher_price']);
                $cart_list['voucher_info']['voucher_enddate_text'] = date('Y年m月d日', $cart_list['voucher_info']['voucher_enddate']);
//                $total_list -= $cart_list['voucher_info']['voucher_price'];
            } else {
                $cart_list['voucher_info'] = array();
            }

            $cart_list['voucher_list'] = array_values($result['voucher_list']);
            if ($result['free_freight_info']['if_free']) {
                $cart_list['freight'] = '0';
                $cart_list['freight_message'] = $result['free_freight_info']['desc'];
            }

        $buy_list = array();
        $buy_list['cart_list'] = $cart_list;
        $buy_list['cart_list_api'] = array_values($cart_list);
        $buy_list['freight_hash'] = $result['freight_list'];
        $buy_list['address_info'] = $result['address_info'];
        $buy_list['vat_deny'] = $result['vat_deny'];
        $buy_list['vat_hash'] = $result['vat_hash'];
        $buy_list['inv_info'] = $result['inv_info'];
        $buy_list['available_predeposit'] = isset($result['available_predeposit']) ? $result['available_predeposit'] : array();
        $buy_list['available_rc_balance'] = isset($result['available_rc_balance']) ? $result['available_rc_balance'] : array();
        $buy_list['member_paypwd'] = isset($result['member_paypwd']) ? $result['member_paypwd'] : false;
        $buy_list['zk_list'] = isset($result['zk_list']) ? $result['zk_list'] : array();

        if (isset($data_area['content']) && $data_area['content']) {
            $total_list = model('buy_1', 'logic')->reCalcGoodsTotal($total_list, $data_area['content'], 'freight');
        }
        $buy_list['order_amount'] = ds_price_format($total_list);
        $buy_list['address_api'] = (isset($data_area) && $data_area) ? $data_area : '';

        $buy_list['final_total_list'] = $total_list;
        ds_json_encode(10000, '', $buy_list);
    }

    /**
     * @api {POST} api/Memberbuy/buy_step2 购物车、直接购买第二步:保存订单入库，产生订单号，开始选择支付方式
     * @apiVersion 3.0.6
     * @apiGroup MemberBuy
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} ifcart 购买数据
     * @apiParam {String} cart_id 购物车ID
     * @apiParam {String} address_id 地址ID
     * @apiParam {String} vat_hash 增值税
     * @apiParam {String} invoice_id 发票ID
     * @apiParam {String} voucher 代金券
     * @apiParam {String} pd_pay 预存款支付金额
     * @apiParam {String} password 支付密码
     * @apiParam {String} rcb_pay 充值卡支付金额
     * @apiParam {String} pay_message 支付留言
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {String} result.pay_sn 支付单号
     * @apiSuccess {String} result.payment_code 支付方式代码
     */
    public function buy_step2()
    {
        $param = array();
        $param['ifcart'] = input('post.ifcart');
        $param['cart_id'] = explode(',', input('post.cart_id'));
        $param['address_id'] = input('post.address_id');
        $param['vat_hash'] = input('post.vat_hash');
        $param['pay_name'] = input('post.pay_name');
        $param['invoice_id'] = input('post.invoice_id');

        $param['pintuan_id'] = input('post.pintuan_id');
        $param['pintuangroup_id'] = input('post.pintuangroup_id');

        //处理代金券
        $voucher = array();
        $post_voucher = explode(',', input('post.voucher'));
        if (!empty($post_voucher)) {
            $voucher = $post_voucher;

        }
        $param['voucher'] = $voucher;
        $param['pay_message'] = input('post.pay_message');
        $param['pd_pay'] = input('post.pd_pay');
        $param['rcb_pay'] = input('post.rcb_pay');
        $param['password'] = input('post.password');
        $param['fcode'] = input('post.fcode');
        $param['order_from'] = get_clienttype();
        $logic_buy = model('buy', 'logic');

        //得到会员等级
        /* $member_model = model('member');
          $member_info = $member_model->getMemberInfoByID($this->member_info['member_id']);
          if ($member_info) {
          $member_gradeinfo = $member_model->getOneMemberGrade(intval($member_info['member_exppoints']));
          $member_discount = $member_gradeinfo['orderdiscount'];
          $member_level = $member_gradeinfo['level'];
          }
          else {
          $member_discount = $member_level = 0;
          } */

        $result = $logic_buy->buyStep2($param, $this->member_info['member_id'], $this->member_info['member_name'], $this->member_info['member_email']);
        if (!$result['code']) {
            ds_json_encode(10001, $result['msg']);
        }
        $order_info = current($result['data']['order_list']);
        $res = array('pay_sn' => $result['data']['pay_sn'], 'payment_code' => $order_info['payment_code']);
        ds_json_encode(10000, '', $res);
    }

    /**
     * 验证密码
     */
    public function check_password()
    {
        if (empty(input('post.password'))) {
            ds_json_encode(10001,'参数错误');
        }

        $member_model = model('member');

        $member_info = $member_model->getMemberInfoByID($this->member_info['member_id']);
        if ($member_info['member_paypwd'] == md5(input('post.password'))) {
            ds_json_encode(10000,'',1);
        }
        else {
            ds_json_encode(10001,'密码错误');
        }
    }

    /**
     * 更换收货地址
     */
    public function change_address()
    {
        $logic_buy = model('buy','logic');
        $city_id = input('post.city_id');
        $area_id = input('post.area_id');
        if (empty($city_id)) {
            $city_id = $area_id;
        }

        $data = $logic_buy->changeAddr(input('post.freight_hash'), $city_id, $area_id, $this->member_info['member_id']);
        if (!empty($data) && $data['state'] == 'success') {
            ds_json_encode(10000,'',$data);
        }
        else {
            ds_json_encode(10001,'地址修改失败');
        }
    }

    /**
     * @api {POST} api/Memberbuy/pay 实物订单支付(新接口)
     * @apiVersion 3.0.6
     * @apiGroup MemberBuy
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} pay_sn 支付单号
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Float} result.member_available_pd  预存款余额
     * @apiSuccess {Float} result.member_available_rcb  充值卡余额
     * @apiSuccess {Boolean} result.member_paypwd  已设置支付密码 true是false否
     * @apiSuccess {Float} result.pay_amount  支付金额
     * @apiSuccess {String} result.pay_sn  支付单号
     * @apiSuccess {Float} result.payed_amount  已支付金额
     * @apiSuccess {Object[]} result.payment_list  支付方式列表
     * @apiSuccess {String} result.payment_list.payment_code  支付方式代码
     * @apiSuccess {String} result.payment_list.payment_name  支付方式名称
     * @apiSuccess {String} result.payment_list.payment_platform  支付方式适用平台
     */
    public function pay()
    {
        $pay_sn = input('post.pay_sn');
        if (!preg_match('/^\d{20}$/', $pay_sn)) {
            ds_json_encode(10001,'该订单不存在');
        }

        //查询支付单信息
        $order_model = model('order');
        $pay_info = $order_model->getOrderpayInfo(array(
                                                      'pay_sn' => $pay_sn, 'buyer_id' => $this->member_info['member_id']
                                                  ));
        if (empty($pay_info)) {
            ds_json_encode(10001,'该订单不存在');
        }

        //取子订单列表
        $condition = array();
        $condition[] = array('pay_sn', '=', $pay_sn);
        $condition[] = array('order_state', 'in', array(ORDER_STATE_NEW, ORDER_STATE_PAY));
        $order_list = $order_model->getOrderList($condition, '', '*', '', 0, array(), true);
        if (empty($order_list)) {
            ds_json_encode(10001,'未找到需要支付的订单');
        }

        //定义输出数组
        $pay = array();
        //支付提示主信息
        //订单总支付金额(不包含货到付款)
        $pay['pay_amount'] = 0;
        //充值卡支付金额(之前支付中止，余额被锁定)
        $pay['payed_rcb_amount'] = 0;
        //预存款支付金额(之前支付中止，余额被锁定)
        $pay['payed_pd_amount'] = 0;
        //还需在线支付金额(之前支付中止，余额被锁定)
        $pay['pay_diff_amount'] = 0;
        //账户可用金额
        $pay['member_available_pd'] = 0;
        $pay['member_available_rcb'] = 0;

        $logic_order = model('order','logic');

        //计算相关支付金额
        foreach ($order_list as $key => $order_info) {
                if ($order_info['order_state'] == ORDER_STATE_NEW) {
                    $pay['payed_rcb_amount'] += $order_info['rcb_amount'];
                    $pay['payed_pd_amount'] += $order_info['pd_amount'];
                    $pay['pay_diff_amount'] += $order_info['order_amount'] - $order_info['rcb_amount'] - $order_info['pd_amount'];
                }
        }
        if (isset($order_info['chain_id']) && $order_info['payment_code'] == 'chain') {
            $order_list[0]['order_remind'] = '下单成功，请在' . CHAIN_ORDER_PAYPUT_DAY . '日内前往门店提货，逾期订单将自动取消。';
            $flag_chain = 1;
        }

        //如果线上线下支付金额都为0，转到支付成功页
        if (empty($pay['pay_diff_amount'])) {
            ds_json_encode(12001,'订单重复支付');
        }

        $condition = array();
        $condition[] = array('payment_platform','=','h5');
        $payment_list = model('payment')->getPaymentOpenList($condition);

        if (!empty($payment_list)) {
            foreach ($payment_list as $k => $value) {
                unset($payment_list[$k]['payment_config']);
                unset($payment_list[$k]['payment_state']);
                unset($payment_list[$k]['payment_state_text']);
            }
        }
        //显示预存款、支付密码、充值卡
        $pay['member_available_pd'] = $this->member_info['available_predeposit'];
        $pay['member_available_rcb'] = $this->member_info['available_rc_balance'];
        $pay['member_paypwd'] = $this->member_info['member_paypwd'] ? true : false;
        $pay['pay_sn'] = $pay_sn;
        $pay['payed_amount'] = ds_price_format($pay['payed_rcb_amount'] + $pay['payed_pd_amount']);
        unset($pay['payed_pd_amount']);
        unset($pay['payed_rcb_amount']);
        $pay['pay_amount'] = ds_price_format($pay['pay_diff_amount']);
        unset($pay['pay_diff_amount']);
        $pay['member_available_pd'] = ds_price_format($pay['member_available_pd']);
        $pay['member_available_rcb'] = ds_price_format($pay['member_available_rcb']);
        $pay['payment_list'] = $payment_list ? array_values($payment_list) : array();
        ds_json_encode(10000,'',array('pay_info' => $pay));
    }

    /**
     * AJAX验证支付密码
     */
    public function check_pd_pwd()
    {
        if (empty(input('post.password'))) {
            ds_json_encode(10001,'支付密码格式不正确');
        }
        $buyer_info = model('member')->getMemberInfoByID($this->member_info['member_id']);
        if ($buyer_info['member_paypwd'] != '') {
            if ($buyer_info['member_paypwd'] === md5(input('post.password'))) {
                ds_json_encode(10000,'',1);
            }
        }
        ds_json_encode(10001,'支付密码验证失败');
    }

    /**
     * F码验证
     */
    public function check_fcode()
    {
        $goods_id = intval(input('post.goods_id'));
        if ($goods_id <= 0) {
            ds_json_encode(10001,'商品ID格式不正确');
        }
        if (input('post.fcode') == '') {
            ds_json_encode(10001,'F码格式不正确');
        }
        $result = model('buy','logic')->checkFcode($goods_id, trim(input('post.fcode')));
        if ($result['code']) {
            ds_json_encode(10000,'',1);
        }
        else {
            ds_json_encode(10001,$result['msg']);
        }
    }
}